package com.thundersoft.mm.phone.bt;

import android.util.Log;


import com.thundersoft.mm.phone.ConnectionManager;

import org.json.JSONObject;

import java.nio.ByteBuffer;
import java.util.UUID;

/**
 * Created by wuchuanlong on 18-2-1.
 */

public class BtTextServerListener extends AbstractBluetoothListener {

    @Override
    public UUID getUUID() {
        return UUID.fromString("84D1319C-1234-644C-901A-8F091F25AF04");
    }

    @Override
    public void processHeadBuffer(byte[] buffer, int count) {

    }

    public PicCallback callback;

    public interface PicCallback{
        public void isLastPic(String type);
    }

    public void setPicCallback(PicCallback callback){
        this.callback=callback;
    }

    @Override
    public synchronized void sendMsg(byte[] bodyByte){
        try {
            if (outputStream != null) {
                if (bodyByte == null || bodyByte.length == 0){
                    throw  new RuntimeException("body is null or length is zero");
                }
                long time = System.currentTimeMillis();

                int len = bodyByte.length;
                int headLength = 0;
                outputLenBuffer.clear();
                byte[] headByte = null;
                if (headByte != null) {
                    headLength = headByte.length;
                }
                // head length
                outputLenBuffer.putInt(headLength);
                // body length
                outputLenBuffer.putInt(len);
                outputLenBuffer.rewind();
                // send head and body length
                outputStream.write(outputLenBuffer.array());
                // send head content
                if (headLength != 0){
                    outputStream.write(headByte);
                }
                // send body content
                outputStream.write(bodyByte);
                outputStream.flush();
                Log.i(TAG,"sendMsg write data take "+(System.currentTimeMillis() - time)+" ms");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void processStream() {
        while(true){
            try {
                if (positionRelease){
                    break;
                }
                try {
                    release();
                    Thread.sleep(200);
                }catch (Exception e){
                    Log.e(TAG,"release error",e);
                }
                listener();
                while(true) {
                    try {
                        /**
                         * read head and body length
                         */
                        byte[] lengthBuffer = new byte[HEAD_BUFFER_SIZE];
                        inputStream.read(lengthBuffer);
                        ByteBuffer headOriBuffer = ByteBuffer.wrap(lengthBuffer);
                        int headLength = headOriBuffer.getInt();
                        int bodyLength = headOriBuffer.getInt();
                        headOriBuffer.clear();
                        lengthBuffer = null;
                        Log.i(TAG,"headLength="+headLength);
                        /**
                         * read head content
                         */
                        int readCount;
                        if (headLength > 0 && headLength < MAX_HEAD_LENGTH){
                            byte[] headBuffer = new byte[headLength];
                            readCount = inputStream.read(headBuffer,0,headLength);
                            processHeadBuffer(headBuffer,readCount);
                            headBuffer = null;
                        }
                        /**
                         * read body content
                         */
                        if (bodyLength > 0 && bodyLength < MAX_BODY_LENGTH) {
                            byte[] bodyBuffer = new byte[bodyLength];
                            readCount = inputStream.read(bodyBuffer,0,bodyLength);
                            processBodyBuffer(bodyBuffer,readCount);
                            bodyBuffer = null;
                        }
//                        sendMsg("来自server消息：已经成功接受数据");
                    }catch (Exception e){
                        Log.e(TAG,"processBodyBuffer error",e);
                        break;
                    }
                }
            } catch (Exception e) {
                Log.i(TAG,"listener bt error : "+e.getLocalizedMessage());
                try {
                    Thread.sleep(1000);
                }catch (Exception e1){}
            }
        }
    }

    @Override
    public void processBodyBuffer(byte[] buffer, int count) {
        try {
            String msg = new String(buffer, 0, count, "utf-8");
            if (!"hearts".equals(msg)){
                JSONObject jsonObject =new JSONObject(msg);
                callback.isLastPic(jsonObject.getString("type"));
                Log.i("processBodyBuffer",jsonObject.getString("type"));
                /*if (msg.contains(ConnectionManager.MSG_START_P2P)){
                    // 启动手机端的wifip2p，开始创建群组
                    ConnectionManager.handler.sendEmptyMessageDelayed(0,50);
                    //=jsonObject.getString("type");
                }*/
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
